#!/usr/bin/env python
#  -*- coding: utf-8 -*-


# 模拟价格变化递归阻塞

import time
import random


START_PRICE = 50  # 起始价位
GRID_AMOUNT = 10  # 网格在多头、空头方向的格子(档位)数量


grid_region_long = [0.05] * GRID_AMOUNT  # 多头每格价格跌幅(网格密度)
grid_region_short = [0.05] * GRID_AMOUNT  # 空头每格价格涨幅(网格密度)
grid_volume_long = [i for i in range(GRID_AMOUNT + 1)]  # 多头每格持仓手数
grid_volume_short = [i for i in range(GRID_AMOUNT + 1)]  # 空头每格持仓手数
grid_prices_long = [reduce(lambda p, r: p * (1 - r), grid_region_long[:i], START_PRICE) for i in
                    range(GRID_AMOUNT + 1)]  # 多头每格的触发价位列表
grid_prices_short = [reduce(lambda p, r: p * (1 + r), grid_region_short[:i], START_PRICE) for i in
                     range(GRID_AMOUNT + 1)]  # 空头每格的触发价位列表



print(grid_region_long)
print(grid_region_short)
print(grid_volume_long)
print(grid_volume_short)
print("多头价格表：")
print(grid_prices_long)
print("空头价格表：")
print(grid_prices_short)

class Api(object):

	def __init__(self, frequency=1, price=100, scale=0.5):
		self.frequency = frequency
		self.price = price
		self.scale = scale

	def wait_update(self):
		
		time.sleep(self.frequency)
		plus =  random.uniform(1, 10)
		if random.randint(0, 1) ==0 :
			self.price += self.scale*plus
		else:
			self.price -= self.scale*plus

	def last_price(self):
		return self.price


api = Api(3, START_PRICE)

def wait_price(layer):

	if(layer >0) or api.last_price() <= grid_prices_long[1]: # 多头
		while True:
			print("-----当前在多头，第%d 层" % (layer))
			print("最新价: %f, 下一层价: %f"  % (api.last_price(), grid_prices_long[layer+1]))
			api.wait_update()
			if layer < GRID_AMOUNT and api.last_price() <= grid_prices_long[layer+1]:
				print("最新价: %f, 进入: 多头第 %d 档" % (api.last_price(), layer + 1))
				wait_price(layer + 1)
				print("已回到多头，第 %d 档" % (layer))
			if api.last_price() > grid_prices_long[layer]:
				print("最新价: %f, 回退到: 多头第 %d 档" % (api.last_price(), layer))
				return
	elif layer <0 or api.last_price >= grid_region_short[1]: #空头
 		layer = -layer

		while True:
			api.wait_update()
			print("-----当前在空头，第%d 层" % (layer))
			print("最新价: %f, 下一层价: %f"  % (api.last_price(), grid_prices_short[layer+1]))
			if layer < GRID_AMOUNT and api.last_price() >= grid_prices_short[layer+1]:
				print("最新价: %f, 进入: 空头第 %d 档" % (api.last_price(), layer + 1))
				wait_price(-(layer + 1))
				print("已回到空头，第 %d 档" % (layer))

			if api.last_price() < grid_prices_short[layer]:
				print("最新价: %f, 回退到: 空头第 %d 档" % (api.last_price(), layer))
				return 


while True:
	api.wait_update()
	print("第一个价格：%f" % (api.last_price()))
	wait_price(0)


